{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 02 魔法命令"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### `%run`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello Machine Learning !\n"
     ]
    }
   ],
   "source": [
    "%run myscript/hello.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello iMooc !\n"
     ]
    }
   ],
   "source": [
    "hello(\"iMooc\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "运行模块"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import mymodule.FirstML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "?\n"
     ]
    }
   ],
   "source": [
    "mymodule.FirstML.predict(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from mymodule import FirstML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "?\n"
     ]
    }
   ],
   "source": [
    "FirstML.predict(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ``%timeit``"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "82.2 μs ± 5.17 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit L = [i**2 for i in range(1000)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "109 ms ± 3.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit L = [i**2 for i in range(1000000)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "992 ns ± 58.5 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%timeit L = [i**2 for i in range(10)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "``%%`` 为区域命令符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "89.2 μs ± 626 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit\n",
    "L = []\n",
    "for n in range(1000):\n",
    "    L.append(n ** 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ``%time``"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "有些时候我们不希望多次执行，使用``%time``"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: total: 0 ns\n",
      "Wall time: 94.2 μs\n"
     ]
    }
   ],
   "source": [
    "%time L = [i**2 for i in range(1000)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: total: 0 ns\n",
      "Wall time: 227 μs\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "L = []\n",
    "for n in range(1000):\n",
    "    L.append(n ** 2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "多次执行命令可能产生问题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "579 μs ± 9.74 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "L = [random.random() for i in range(100000)] \n",
    "%timeit L.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: total: 46.9 ms\n",
      "Wall time: 23.8 ms\n"
     ]
    }
   ],
   "source": [
    "L = [random.random() for i in range(100000)] \n",
    "%time L.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 4.26 ms, sys: 3 µs, total: 4.26 ms\n",
      "Wall time: 4.27 ms\n"
     ]
    }
   ],
   "source": [
    "%time L.sort()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 其他魔法命令："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/json": {
       "cell": {
        "!": "OSMagics",
        "HTML": "Other",
        "SVG": "Other",
        "bash": "Other",
        "capture": "ExecutionMagics",
        "cmd": "Other",
        "code_wrap": "ExecutionMagics",
        "debug": "ExecutionMagics",
        "file": "Other",
        "html": "DisplayMagics",
        "javascript": "DisplayMagics",
        "js": "DisplayMagics",
        "latex": "DisplayMagics",
        "markdown": "DisplayMagics",
        "perl": "Other",
        "prun": "ExecutionMagics",
        "pypy": "Other",
        "python": "Other",
        "python2": "Other",
        "python3": "Other",
        "ruby": "Other",
        "script": "ScriptMagics",
        "sh": "Other",
        "svg": "DisplayMagics",
        "sx": "OSMagics",
        "system": "OSMagics",
        "time": "ExecutionMagics",
        "timeit": "ExecutionMagics",
        "writefile": "OSMagics"
       },
       "line": {
        "alias": "OSMagics",
        "alias_magic": "BasicMagics",
        "autoawait": "AsyncMagics",
        "autocall": "AutoMagics",
        "automagic": "AutoMagics",
        "autosave": "KernelMagics",
        "bookmark": "OSMagics",
        "cd": "OSMagics",
        "clear": "KernelMagics",
        "cls": "KernelMagics",
        "code_wrap": "ExecutionMagics",
        "colors": "BasicMagics",
        "conda": "PackagingMagics",
        "config": "ConfigMagics",
        "connect_info": "KernelMagics",
        "copy": "Other",
        "ddir": "Other",
        "debug": "ExecutionMagics",
        "dhist": "OSMagics",
        "dirs": "OSMagics",
        "doctest_mode": "BasicMagics",
        "echo": "Other",
        "ed": "Other",
        "edit": "KernelMagics",
        "env": "OSMagics",
        "gui": "BasicMagics",
        "hist": "Other",
        "history": "HistoryMagics",
        "killbgscripts": "ScriptMagics",
        "ldir": "Other",
        "less": "KernelMagics",
        "load": "CodeMagics",
        "load_ext": "ExtensionMagics",
        "loadpy": "CodeMagics",
        "logoff": "LoggingMagics",
        "logon": "LoggingMagics",
        "logstart": "LoggingMagics",
        "logstate": "LoggingMagics",
        "logstop": "LoggingMagics",
        "ls": "Other",
        "lsmagic": "BasicMagics",
        "macro": "ExecutionMagics",
        "magic": "BasicMagics",
        "mamba": "PackagingMagics",
        "matplotlib": "PylabMagics",
        "micromamba": "PackagingMagics",
        "mkdir": "Other",
        "more": "KernelMagics",
        "notebook": "BasicMagics",
        "page": "BasicMagics",
        "pastebin": "CodeMagics",
        "pdb": "ExecutionMagics",
        "pdef": "NamespaceMagics",
        "pdoc": "NamespaceMagics",
        "pfile": "NamespaceMagics",
        "pinfo": "NamespaceMagics",
        "pinfo2": "NamespaceMagics",
        "pip": "PackagingMagics",
        "popd": "OSMagics",
        "pprint": "BasicMagics",
        "precision": "BasicMagics",
        "prun": "ExecutionMagics",
        "psearch": "NamespaceMagics",
        "psource": "NamespaceMagics",
        "pushd": "OSMagics",
        "pwd": "OSMagics",
        "pycat": "OSMagics",
        "pylab": "PylabMagics",
        "qtconsole": "KernelMagics",
        "quickref": "BasicMagics",
        "recall": "HistoryMagics",
        "rehashx": "OSMagics",
        "reload_ext": "ExtensionMagics",
        "ren": "Other",
        "rep": "Other",
        "rerun": "HistoryMagics",
        "reset": "NamespaceMagics",
        "reset_selective": "NamespaceMagics",
        "rmdir": "Other",
        "run": "ExecutionMagics",
        "save": "CodeMagics",
        "sc": "OSMagics",
        "set_env": "OSMagics",
        "store": "StoreMagics",
        "sx": "OSMagics",
        "system": "OSMagics",
        "tb": "ExecutionMagics",
        "time": "ExecutionMagics",
        "timeit": "ExecutionMagics",
        "unalias": "OSMagics",
        "unload_ext": "ExtensionMagics",
        "uv": "PackagingMagics",
        "who": "NamespaceMagics",
        "who_ls": "NamespaceMagics",
        "whos": "NamespaceMagics",
        "xdel": "NamespaceMagics",
        "xmode": "BasicMagics"
       }
      },
      "text/plain": [
       "Available line magics:\n",
       "%alias  %alias_magic  %autoawait  %autocall  %automagic  %autosave  %bookmark  %cd  %clear  %cls  %code_wrap  %colors  %conda  %config  %connect_info  %copy  %ddir  %debug  %dhist  %dirs  %doctest_mode  %echo  %ed  %edit  %env  %gui  %hist  %history  %killbgscripts  %ldir  %less  %load  %load_ext  %loadpy  %logoff  %logon  %logstart  %logstate  %logstop  %ls  %lsmagic  %macro  %magic  %mamba  %matplotlib  %micromamba  %mkdir  %more  %notebook  %page  %pastebin  %pdb  %pdef  %pdoc  %pfile  %pinfo  %pinfo2  %pip  %popd  %pprint  %precision  %prun  %psearch  %psource  %pushd  %pwd  %pycat  %pylab  %qtconsole  %quickref  %recall  %rehashx  %reload_ext  %ren  %rep  %rerun  %reset  %reset_selective  %rmdir  %run  %save  %sc  %set_env  %store  %sx  %system  %tb  %time  %timeit  %unalias  %unload_ext  %uv  %who  %who_ls  %whos  %xdel  %xmode\n",
       "\n",
       "Available cell magics:\n",
       "%%!  %%HTML  %%SVG  %%bash  %%capture  %%cmd  %%code_wrap  %%debug  %%file  %%html  %%javascript  %%js  %%latex  %%markdown  %%perl  %%prun  %%pypy  %%python  %%python2  %%python3  %%ruby  %%script  %%sh  %%svg  %%sx  %%system  %%time  %%timeit  %%writefile\n",
       "\n",
       "Automagic is ON, % prefix IS NOT needed for line magics."
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%lsmagic"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31mDocstring:\u001b[39m\n",
      "Run the named file inside IPython as a program.\n",
      "\n",
      "Usage::\n",
      "\n",
      "  %run [-n -i -e -G]\n",
      "       [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]\n",
      "       ( -m mod | filename ) [args]\n",
      "\n",
      "The filename argument should be either a pure Python script (with\n",
      "extension ``.py``), or a file with custom IPython syntax (such as\n",
      "magics). If the latter, the file can be either a script with ``.ipy``\n",
      "extension, or a Jupyter notebook with ``.ipynb`` extension. When running\n",
      "a Jupyter notebook, the output from print statements and other\n",
      "displayed objects will appear in the terminal (even matplotlib figures\n",
      "will open, if a terminal-compliant backend is being used). Note that,\n",
      "at the system command line, the ``jupyter run`` command offers similar\n",
      "functionality for executing notebooks (albeit currently with some\n",
      "differences in supported options).\n",
      "\n",
      "Parameters after the filename are passed as command-line arguments to\n",
      "the program (put in sys.argv). Then, control returns to IPython's\n",
      "prompt.\n",
      "\n",
      "This is similar to running at a system prompt ``python file args``,\n",
      "but with the advantage of giving you IPython's tracebacks, and of\n",
      "loading all variables into your interactive namespace for further use\n",
      "(unless -p is used, see below).\n",
      "\n",
      "The file is executed in a namespace initially consisting only of\n",
      "``__name__=='__main__'`` and sys.argv constructed as indicated. It thus\n",
      "sees its environment as if it were being run as a stand-alone program\n",
      "(except for sharing global objects such as previously imported\n",
      "modules). But after execution, the IPython interactive namespace gets\n",
      "updated with all variables defined in the program (except for ``__name__``\n",
      "and ``sys.argv``). This allows for very convenient loading of code for\n",
      "interactive work, while giving each program a 'clean sheet' to run in.\n",
      "\n",
      "Arguments are expanded using shell-like glob match.  Patterns\n",
      "'*', '?', '[seq]' and '[!seq]' can be used.  Additionally,\n",
      "tilde '~' will be expanded into user's home directory.  Unlike\n",
      "real shells, quotation does not suppress expansions.  Use\n",
      "*two* back slashes (e.g. ``\\\\*``) to suppress expansions.\n",
      "To completely disable these expansions, you can use -G flag.\n",
      "\n",
      "On Windows systems, the use of single quotes `'` when specifying\n",
      "a file is not supported. Use double quotes `\"`.\n",
      "\n",
      "Options:\n",
      "\n",
      "-n\n",
      "  __name__ is NOT set to '__main__', but to the running file's name\n",
      "  without extension (as python does under import).  This allows running\n",
      "  scripts and reloading the definitions in them without calling code\n",
      "  protected by an ``if __name__ == \"__main__\"`` clause.\n",
      "\n",
      "-i\n",
      "  run the file in IPython's namespace instead of an empty one. This\n",
      "  is useful if you are experimenting with code written in a text editor\n",
      "  which depends on variables defined interactively.\n",
      "\n",
      "-e\n",
      "  ignore sys.exit() calls or SystemExit exceptions in the script\n",
      "  being run.  This is particularly useful if IPython is being used to\n",
      "  run unittests, which always exit with a sys.exit() call.  In such\n",
      "  cases you are interested in the output of the test results, not in\n",
      "  seeing a traceback of the unittest module.\n",
      "\n",
      "-t\n",
      "  print timing information at the end of the run.  IPython will give\n",
      "  you an estimated CPU time consumption for your script, which under\n",
      "  Unix uses the resource module to avoid the wraparound problems of\n",
      "  time.clock().  Under Unix, an estimate of time spent on system tasks\n",
      "  is also given (for Windows platforms this is reported as 0.0).\n",
      "\n",
      "  If -t is given, an additional ``-N<N>`` option can be given, where <N>\n",
      "  must be an integer indicating how many times you want the script to\n",
      "  run.  The final timing report will include total and per run results.\n",
      "\n",
      "  For example (testing the script uniq_stable.py)::\n",
      "\n",
      "      In [1]: run -t uniq_stable\n",
      "\n",
      "      IPython CPU timings (estimated):\n",
      "        User  :    0.19597 s.\n",
      "        System:        0.0 s.\n",
      "\n",
      "      In [2]: run -t -N5 uniq_stable\n",
      "\n",
      "      IPython CPU timings (estimated):\n",
      "      Total runs performed: 5\n",
      "        Times :      Total       Per run\n",
      "        User  :   0.910862 s,  0.1821724 s.\n",
      "        System:        0.0 s,        0.0 s.\n",
      "\n",
      "-d\n",
      "  run your program under the control of pdb, the Python debugger.\n",
      "  This allows you to execute your program step by step, watch variables,\n",
      "  etc.  Internally, what IPython does is similar to calling::\n",
      "\n",
      "      pdb.run('execfile(\"YOURFILENAME\")')\n",
      "\n",
      "  with a breakpoint set on line 1 of your file.  You can change the line\n",
      "  number for this automatic breakpoint to be <N> by using the -bN option\n",
      "  (where N must be an integer). For example::\n",
      "\n",
      "      %run -d -b40 myscript\n",
      "\n",
      "  will set the first breakpoint at line 40 in myscript.py.  Note that\n",
      "  the first breakpoint must be set on a line which actually does\n",
      "  something (not a comment or docstring) for it to stop execution.\n",
      "\n",
      "  Or you can specify a breakpoint in a different file::\n",
      "\n",
      "      %run -d -b myotherfile.py:20 myscript\n",
      "\n",
      "  When the pdb debugger starts, you will see a (Pdb) prompt.  You must\n",
      "  first enter 'c' (without quotes) to start execution up to the first\n",
      "  breakpoint.\n",
      "\n",
      "  Entering 'help' gives information about the use of the debugger.  You\n",
      "  can easily see pdb's full documentation with \"import pdb;pdb.help()\"\n",
      "  at a prompt.\n",
      "\n",
      "-p\n",
      "  run program under the control of the Python profiler module (which\n",
      "  prints a detailed report of execution times, function calls, etc).\n",
      "\n",
      "  You can pass other options after -p which affect the behavior of the\n",
      "  profiler itself. See the docs for %prun for details.\n",
      "\n",
      "  In this mode, the program's variables do NOT propagate back to the\n",
      "  IPython interactive namespace (because they remain in the namespace\n",
      "  where the profiler executes them).\n",
      "\n",
      "  Internally this triggers a call to %prun, see its documentation for\n",
      "  details on the options available specifically for profiling.\n",
      "\n",
      "There is one special usage for which the text above doesn't apply:\n",
      "if the filename ends with .ipy[nb], the file is run as ipython script,\n",
      "just as if the commands were written on IPython prompt.\n",
      "\n",
      "-m\n",
      "  specify module name to load instead of script path. Similar to\n",
      "  the -m option for the python interpreter. Use this option last if you\n",
      "  want to combine with other %run options. Unlike the python interpreter\n",
      "  only source modules are allowed no .pyc or .pyo files.\n",
      "  For example::\n",
      "\n",
      "      %run -m example\n",
      "\n",
      "  will run the example module.\n",
      "\n",
      "-G\n",
      "  disable shell-like glob expansion of arguments.\n",
      "\u001b[31mFile:\u001b[39m      d:\\programdata\\miniconda3\\envs\\py_test\\lib\\site-packages\\ipython\\core\\magics\\execution.py"
     ]
    }
   ],
   "source": [
    "%run?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py_test",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
